package com.eliza.base.entity.model.user

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.eliza.library.data.entity.UserEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class UserViewModel @Inject constructor(
    private val repo: UserRepository
) : ViewModel() {
//    @Inject   lateinit var repo: UserRepository

    private var _allFlow: Flow<List<UserEntity>> = MutableStateFlow(emptyList())
    private var list: MutableStateFlow<List<UserEntity>> = MutableStateFlow(emptyList())
    private var _live: LiveData<List<UserEntity>> = MutableLiveData(emptyList())
    private var topMovies = _live
    fun getAllFlow(): Flow<List<UserEntity>> {
        viewModelScope.launch {
            _allFlow = repo.getAllFlow()
            _allFlow.flowOn(Dispatchers.IO).collect {
                list.value = it
            }
        }
        return _allFlow
    }

    fun getAllNormal(): LiveData<List<UserEntity>> {
        _live = repo.getAllNormal()
        return topMovies
    }

    fun insert(item: List<UserEntity>) = viewModelScope.launch {
        repo.insert(item)
    }

    fun getByName(name: String): Flow<List<UserEntity>> {
        viewModelScope.launch {
            _allFlow = repo.getByName(name)
        }
        return _allFlow
    }

    suspend fun deleteById(id: UserEntity) {
        return repo.deleteById(id)
    }
}

